<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { getAllImg, deleteImg } from '@/api/homemanage';
// import { globals } from "@/main";

// const serverUrl = ref(globals.$config?.serverUrl + "/home/uploadImg")

const uploadRef = ref()

const headers = { Authorization: localStorage.getItem('Authorization') }

const tableData = reactive([])

async function getTable() {
  tableData.length = 0
  let images = await (await getAllImg()).data
  // tableData.push(images.data)
  for (let i = 0; i < images.length; i++) {
    // console.log(res.data[i])
    tableData.push(images[i])
  }
  // console.log(tableData)
}
getTable()

const handleDelete = async (id) => {
  await deleteImg(id)
  ElMessage.success("删除成功！")
  getTable()
}

const submitUpload = () => {
  if (uploadRef.value !== null) {
    uploadRef.value.submit()
  } else {
    ElMessage.error('上传列表为空')
  }
}

const uploadSuccess = () => {
  ElMessage.success("上传成功！")
  uploadRef.value.clearFiles()
  getTable()
}
const uploadError = () => {
  ElMessage.error("上传失败！")
  uploadRef.value.clearFiles()
}
const handleExceed = () => {
  ElMessage.error("上传文件超出限制，请重新选择")
  uploadRef.value.clearFiles()
}

</script>

<template>
  <div>
    <div style="padding: 25px;margin-left: 30px;">
      <el-upload ref="uploadRef" action="http//:localhost:9191/home/uploadImg" :auto-upload="false" :on-success="uploadSuccess"
        :on-error="uploadError" :limit="5" :on-exceed="handleExceed" :headers="headers">
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>

        <el-button type="success" @click="submitUpload" style="margin-left: 10px;">
          上 传
        </el-button>
        <template #tip>
          <div class="el-upload__tip">
            请上传500kb以内的jpg/png文件
          </div>
        </template>
      </el-upload>
    </div>

    <el-table :data="tableData" style="width:100vh;height: 700px;" show-header>
      <el-table-column fixed label="id" prop="id" sortable />
      <el-table-column label="封面" prop="url">
        <template #default="scope">
          <el-image style="height: 150px;" :src="scope.row.url" :preview-src-list="[scope.row.url]"
            preview-teleported="true" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width='200px'>
        <template #default="scope">
          <el-button size="large" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
